"""
通用工具函数
"""
import os
import time
import random
import logging
from datetime import datetime
from typing import Optional


def setup_logging(log_file: str = "logs/ticket_boost.log") -> logging.Logger:
    """设置日志记录"""
    # 确保日志目录存在
    os.makedirs(os.path.dirname(log_file), exist_ok=True)
    
    # 配置日志格式
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    # 创建文件处理器
    file_handler = logging.FileHandler(log_file, encoding='utf-8')
    file_handler.setFormatter(formatter)
    
    # 创建控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    
    # 配置根日志记录器
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    
    # 清除现有处理器
    logger.handlers = []
    
    # 添加处理器
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    
    return logger


def random_sleep(min_seconds: float = 0.5, max_seconds: float = 2.0) -> None:
    """随机等待时间"""
    sleep_time = random.uniform(min_seconds, max_seconds)
    time.sleep(sleep_time)


def get_current_time() -> str:
    """获取当前时间字符串"""
    return datetime.now().strftime('%Y-%m-%d %H:%M:%S')


def play_notification_sound() -> None:
    """播放提示音"""
    try:
        import winsound
        # 播放系统提示音
        winsound.MessageBeep(winsound.MB_ICONHAND)
    except ImportError:
        try:
            # Linux/Mac 系统
            os.system('echo -e "\\007"')
        except:
            pass


def show_notification(title: str, message: str) -> None:
    """显示系统通知"""
    try:
        import win10toast
        toaster = win10toast.ToastNotifier()
        toaster.show_toast(title, message, duration=5)
    except ImportError:
        try:
            # Linux 系统
            os.system(f'notify-send "{title}" "{message}"')
        except:
            print(f"通知: {title} - {message}")


def safe_filename(filename: str) -> str:
    """生成安全的文件名"""
    # 替换不安全的字符
    unsafe_chars = ['<', '>', ':', '"', '/', '\\', '|', '?', '*']
    for char in unsafe_chars:
        filename = filename.replace(char, '_')
    return filename


def generate_screenshot_filename() -> str:
    """生成截图文件名"""
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    return f"logs/screenshot_{timestamp}.png"


class RetryHelper:
    """重试助手类"""
    
    def __init__(self, max_retries: int = 3, delay: float = 1.0, backoff: float = 2.0):
        self.max_retries = max_retries
        self.delay = delay
        self.backoff = backoff
    
    def retry(self, func, *args, **kwargs):
        """执行重试逻辑"""
        last_exception = None
        
        for attempt in range(self.max_retries + 1):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                last_exception = e
                if attempt < self.max_retries:
                    sleep_time = self.delay * (self.backoff ** attempt)
                    time.sleep(sleep_time)
                    continue
                else:
                    break
        
        # 如果所有重试都失败，抛出最后一个异常
        if last_exception:
            raise last_exception